<template>
	<view class="safe-area-inset-bottom drawCard">
		<u-navbar :back-icon-size="24" :status-bar-height="0">
			<view slot="" class="slot-wrap">
				<text>制作模卡</text>
				<view class="nav_btn">
					<u-button type="success" :custom-style="customStyle" @click="drawCard">成功按钮</u-button>
				</view>
			</view>
		</u-navbar>
		<template v-if="!drawed">
		<view class="card">
			<view class="info">
				<text>张三</text>
			</view>
				<view class="item_one" :style="{width: langwidthJS(234) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#333', position: 'absolute', left: langwidthJS(121) + 'px', top: langwidthJS(56) + 'px'} ">
					<movable-area :style="{width: langwidthJS(234) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#747474',}">
						<movable-view :style="{width: langwidthJS(234) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#747474',}" scale scale-min="1" scale-max="2" @scale="bindscale" :data-pic-idx="0">
							<scroll-view scroll-x scroll-y :style="{width: langwidthJS(234) + 'px', height: langwidthJS(354) + 'px'}" id="scrollImg0">
								<image id="image0" :style="{width: langwidthJS(234) + 'px', height: langwidthJS(354) + 'px'}" :src="tempFilePaths[0].picUrl" mode="scaleToFill" class="img-box" @touchstart="touchStart" @touchend="touchEnd" :data-pic-idx="0"></image>
							</scroll-view>
						</movable-view>
					</movable-area>
				</view>
				<view class="item_two" :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#333', position: 'absolute', left: langwidthJS(360) + 'px', top: langwidthJS(56) + 'px'}">
					<movable-area :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#747474',}">
						<movable-view :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#747474',}" scale scale-min="1" scale-max="2" @scale="bindscale" :data-pic-idx="1">
							<scroll-view scroll-x scroll-y :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px'}" id="scrollImg1">
								<image id="image1" :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px'}" :src="tempFilePaths[1].picUrl" mode="scaleToFill" class="img-box" @touchstart="touchStart" @touchend="touchEnd" :data-pic-idx="1"></image>
							</scroll-view>
						</movable-view>
					</movable-area>
				</view>
				<view class="item_three" :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#747474', position: 'absolute', top: langwidthJS(238)+ 'px', left: langwidthJS(360)+'px'}">
					<movable-area :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#747474',}">
						<movable-view :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px', backgroundColor: '#747474',}" scale scale-min="1" scale-max="2" @scale="bindscale" :data-pic-idx="2">
							<scroll-view scroll-x scroll-y :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px'}" id="scrollImg1">
								<image id="image2" :style="{width: langwidthJS(252) + 'px', height: langwidthJS(177) + 'px'}" :src="tempFilePaths[2].picUrl" mode="scaleToFill" class="img-box" @touchstart="touchStart" @touchend="touchEnd" :data-pic-idx="2"></image>
							</scroll-view>
						</movable-view>
					</movable-area>
				</view>
				<view class="item_four" :style="{width: langwidthJS(434) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#747474', position: 'absolute', left: langwidthJS(617) + 'px', top: langwidthJS(56) + 'px'}">
					<movable-area :style="{width: langwidthJS(434) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#747474',}">
						<movable-view :style="{width: langwidthJS(434) + 'px', height: langwidthJS(354) + 'px', backgroundColor: '#747474',}" scale scale-min="1" scale-max="2" @scale="bindscale" :data-pic-idx="3">
							<scroll-view scroll-x scroll-y :style="{width: langwidthJS(434) + 'px', height: langwidthJS(354) + 'px'}" id="scrollImg1">
								<image id="image3" :style="{width: langwidthJS(434) + 'px', height: langwidthJS(354) + 'px'}" :src="tempFilePaths[3].picUrl" mode="scaleToFill" class="img-box" @touchstart="touchStart" @touchend="touchEnd" :data-pic-idx="3"></image>
							</scroll-view>
						</movable-view>
					</movable-area>
				</view>
		</view>
		<canvas canvas-id='cardcanvas' :style="{width: canvasW + 'px', height: canvasH + 'px', marginTop: '1000px'}" class="" v-if="showing"></canvas>
		</template>
		<u-mask :show="drawed" @click="drawed = false">
			<view class="showImage">
				<image class="draw-card" :src="card"></image>
				<button class="base-btn mt50 mb20" @click="saveCard">保存卡片</button>
			</view>
		</u-mask>
		
	</view>
</template>

<script>
	import drawCardUtils from '../../config/public.js'
	export default {
		data() {
			return {
				drawed: false,
				showing: false,
				customStyle: {
					fontSize: '12px',
					width: '40rpx',
					height: '30rpx'
				},
				userinfo: {
					name: '张三',
					height: '188',
					weight: '75',
					chest: '70',
					waist: '60',
					hip:'65',
					shooseSize: '46'
				},
				tempFilePaths: [
					{
						x: 0,
						y: 0,
						scale: 1, // 图片双指缩放倍数，默认没有缩放就是1
						picUrl: 'https://qkj.cdgsxq.com/driver604f304fa3bd627.jpeg',
						left: 0,
						top: 0,
						lastLeft: 0,
						lastTop: 0,
						width: this.langwidthJS(234),
						height: this.langwidthJS(354)
					},
					{
						x: 0,
						y: 0,
						scale: 1,
						picUrl: 'https://qkj.cdgsxq.com/123.png',
						left: 0,
						top: 0,
						lastLeft: 0,
						lastTop: 0,
						width: this.langwidthJS(252),
						height: this.langwidthJS(177)
					},
					{
						x: 0,
						y: 0,
						scale: 1,
						picUrl: 'https://qkj.cdgsxq.com/1599546496151_img_.jpg',
						left: 0,
						top: 0,
						lastLeft: 0,
						lastTop: 0,
						width: this.langwidthJS(252),
						height: this.langwidthJS(177)
					},
					{
						x: 0,
						y: 0,
						scale: 1,
						picUrl: 'https://qkj.cdgsxq.com/cloud_banner.png',
						left: 0,
						top: 0,
						lastLeft: 0,
						lastTop: 0,
						width: this.langwidthJS(234),
						height: this.langwidthJS(354)
					}
				],
				start: -1,
				end: -1,
				WIDTH: 0, // 屏幕宽
				HEIGHT: 0, // 屏幕高
				canvasW: 0, // 画布宽
				canvasH: 0,	// 画布高
				ctx: null,
				card: ''
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					console.log(res.windowWidth, res.windowHeight)
				}
			})
		},
		onReady() {
			this.init()
		},
		methods: {
			langwidthJS(number) {
				return (750 * number / 812)
			},
			scroll(e) {
				console.log(e)
			},
			init() {
				uni.getSystemInfo({
					success: (res) => {
						this.WIDTH = res.windowWidth
						this.HEIGHT = res.windowHeight
						this.canvasW = res.windowWidth
						this.canvasH = res.windowHeight
					}
				})
				drawCardUtils.getAllRects('.img-box').then((rects) => {
					console.log(rects)
					rects.forEach((rect, idx) => {
						this.tempFilePaths[idx].left = rect.left
						this.tempFilePaths[idx].top = rect.top
					})
					console.log(this.tempFilePaths)
				})
			},
			// 触摸开始
			touchStart (e) {
			  const self = this;
			  // 触摸开始时的图片下标
			  this.start = e.currentTarget.dataset.picIdx;
				console.log(this.start)
			},
			
			// 触摸结束
			touchEnd(e) {
				console.log(e)
			  const endX = e.changedTouches[0].x || e.changedTouches[0].pageX;
			  const endY = e.changedTouches[0].y || e.changedTouches[0].pageY;
			  // 判断触摸停止的位置时注意都要加上相应的边距距离再与xy轴的坐标相比较
			  if (endY < this.langwidthJS(354) && endX < (this.langwidthJS(234) + this.langwidthJS(121))) {
			    this.end = 0
			  } else if (endX > this.langwidthJS(360) && endX < (this.langwidthJS(360) + this.langwidthJS(252)) && endY < this.langwidthJS(177) + this.langwidthJS(56)) {
			    this.end = 1;
			  } else if (endX > this.langwidthJS(360) && endX < (this.langwidthJS(360) + this.langwidthJS(252)) && endY > (this.langwidthJS(177) + this.langwidthJS(56)) && endY < this.langwidthJS(177) * 2) {
					this.end = 2;
				} else if (endX > this.langwidthJS(618)) {
					this.end = 3;
				}
			  // 如果开始和结束的触摸点是同一张图片不做操作
			  if (this.start === this.end) {
			    return;
			  } else {
					console.log(this.end)
			    // 否则图片进行交换, 注意只交换图片
			    let temp = this.tempFilePaths[this.start].picUrl;
			    this.tempFilePaths[this.start].picUrl = this.tempFilePaths[this.end].picUrl;
			    this.tempFilePaths[this.end].picUrl = temp;
			  }
			},
			
			getImgBox(idx) {
				return new Promise((resolve, reject) => {
					uni.createSelectorQuery().select(`#image${idx}`).boundingClientRect(rect => {
						console.log(rect)
						this.tempFilePaths[idx].lastLeft = rect.left || 0;
						this.tempFilePaths[idx].lastTop = rect.top || 0;
						resolve();
					}).exec();
				})
			},
			
			// 双指缩放
			bindscale(e) {
				let scale = e.detail.scale;
				let idx = e.currentTarget.dataset.picIdx;
				this.tempFilePaths[idx].scale = scale
			},
			
			// 开始制作卡片
			drawCard() {
				uni.showLoading({
					title: '正在制作'
				})
				this.showing = true
				this.ctx = uni.createCanvasContext("cardcanvas");
				this.ctx.rect(0, 0, this.canvasW, this.canvasH);
				this.ctx.setFillStyle('white');
				this.ctx.fill();
				// 先画图片
				this.drawPic(0)
			},
			
			// 画图片
			drawPic(idx) {
				let self = this
				const t = this.tempFilePaths[idx]
				console.log(t)
				// 记录图片的缩放比
				let widthScale = 1;
				let heightScale = 1;
				// 记录画布开始坐标，留4像素的空白
				let canvasX = t.left;
				let canvasY = t.top - 48;
				let pw = t.width
				let ph = t.height
				new Promise((resolve, reject) => {
					// 获取图片容器大小
					drawCardUtils.getFields(idx).then(res => {
						const viewWH = res[0];
						// 获取图片原始尺寸
						drawCardUtils.getImgInfo(t.picUrl).then(res => {
							// 换成本地图片
							t.picUrl = res.path
							// 计算图片缩放比
							widthScale = res.width / viewWH.width;
							heightScale = res.height / viewWH.height;
							// 获取图像最终坐标
							self.getImgBox(idx).then(res => {
								console.log(t)
								// 图像开始画的位置
								let picX = !t.lastLeft ? t.x : (t.left - t.lastLeft) * widthScale;
								let picY = !t.lastTop ? t.y : (t.top - t.lastTop) * heightScale;
								if(idx == 1) {
									// 画第二张，画布坐标画布宽高调整
									canvasX = t.left;
									canvasY = t.top - 48;
									pw = t.width; 
									ph = t.height;
								} else if (idx == 2) {
									// 画第三张
									canvasX = t.left;
									canvasY = t.top - 48;
									pw = t.width;
									ph = t.height;
								} else if (idx == 3) {
									canvasX = t.left;
									canvasY = t.top - 48;
									pw = t.width ;
									ph = t.height;
								};
								self.ctx.drawImage(
									t.picUrl, // 图像路径
									picX * t.scale, // 图像坐标(要乘以双指缩放倍数)
									picY * t.scale,
									pw * widthScale,// 图像宽
									ph * heightScale,// 图像高 
									canvasX, canvasY, pw, ph // 画布坐标  画布宽高
								);
								console.log(t.picUrl, picX * t.scale, picY * t.scale, pw * widthScale, ph * heightScale,canvasX, canvasY, pw, ph)
								self.ctx.draw(true)
								// 画图有延迟
								setTimeout(() => {
									resolve();
								}, 100);
							})
						})
					})
				}).then(() => {
					idx++;
					if(idx < self.tempFilePaths.length) {
						self.drawPic(idx);
					} else {
						// 画用户信息
						let nameFS = 13;
						let detailFS = 10;
						if (self.WIDTH === 320) {
							nameFS = 11;
							detailFS = 8;
						};
						// 为适配各种机型，画布的横坐标都以屏幕的宽计算， 纵坐标以定义的图片的高度来计算
						self.ctx.setFillStyle("#000000");
						self.ctx.setFontSize(nameFS);
						self.ctx.setTextBaseline('middle');
						self.ctx.fillText(self.userinfo.name, self.WIDTH / 22, 30);
						self.ctx.setFontSize(detailFS);
						let text = '身高 ' + self.userinfo.height + 'cm';
						self.ctx.fillText(text, self.WIDTH / 22, 50);
						
						text = '体重 ' + self.userinfo.weight + 'kg';
						self.ctx.fillText(text, self.WIDTH / 22, 70);
						
						text = '三围 ' + self.userinfo.chest + '/' + self.userinfo.waist + '/' + self.userinfo.hip;
						self.ctx.fillText(text, self.WIDTH / 22, 90);
						
						text = '鞋码 ' + self.userinfo.shooseSize;
						self.ctx.fillText(text, self.WIDTH / 22, 110);
						
						self.ctx.closePath();
						self.ctx.setStrokeStyle('#fff')
						self.ctx.stroke();
						self.ctx.clip();
						
						self.ctx.restore();
						self.ctx.draw(true);
						self.canvasToImg(self.ctx)
					}
				})
			},
			
			canvasToImg() {
				let self = this
				let image = '';
				uni.canvasToTempFilePath({
					canvasId: 'cardcanvas',
					x: 0,
					y: 0,
					width: self.WIDTH,
					height: self.HEIGHT,
					destWidth: 3160,
					destHeight: 1240,
					success: (res) => {
						uni.hideLoading();
						image = res.tempFilePath;
						self.card = image
						self.showing = false
						self.drawed = true
						if(!res.tempFilePath) {
							uni.showToast({
								title: '制作卡片出错',
								duration: 3000,
								icon: 'none'
							})
							return
						}
						// 保存卡片
						// self.saveCard();
					},
					fail: (err) => {
						uni.hideLoading();
						self.showing = true;
						console.log('导出画布内容失败fail err:', err)
					}
				})
			},
			
			saveCard() {
				uni.showLoading({
					title: '保存中'
				})
				let card = this.card;
				uni.saveImageToPhotosAlbum({
					filePath: card,
					success: (res) => {
						uni.hideLoading()
						uni.showToast({
							title:'保存成功',
							duration:3000
						})
					},
					fail: (err) => {
						uni.hideLoading()
						console.log(err)
						uni.showToast({
							icon:'none',
							title: '保存图片出错',
							duration:3000
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@function langwidth($width) {
	   @return 750 * $width / 812;
	}
	.drawCard {
		padding-bottom: env(safe-area-inset-bottom);
		padding-bottom: constant(safe-area-inset-bottom);
		min-height: 100vh;
	}
	.slot-wrap {
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		flex: 1;
		padding: 0 30rpx;
		font-size: 16px;
	}
	.card {
		display: flex;
		flex-direction: row;
	}
	.info {
		width: langwidth(121px);
		padding-left: env(safe-area-inset-bottom);
		padding-left: constant(safe-area-inset-bottom);
		padding: langwidth(8px) langwidth(20px);
	}
	image {
		overflow: hidden;
	}
	.showImage {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-top: 50rpx;
		image {
			width: 70vw;
		}
	}
	.scroll-view_H {
		.-webkit-scrollbar {
			background-color: red;
		}
	}
</style>
